<?php

namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
use Zend\View\Model\ViewModel;
use Zend\Validator\File\NotExists;
use Users\Form\UploadForm;
//use Users\Model\UploadTable;
use Users\Model\Upload;
//use Users\Form\AddsharingForm;
//use Zend\Filter\RealPath;
//use Users\Form\RegisterForm;


class UpploadmanagerController extends AbstractActionController
{
	protected $_dir = NULL;
	protected $uploadFiles;
	//protected $LastUploadFiles;
	protected $filename;
	protected  $authservice;
	
	public function init()
	{
		$config = $this->getServiceLocator()->get('config');
		//$fileManagerDir = $config['file_manager']['dir'];
		$fileManagerDir = $config['module_config']['upload_location'];
		$userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
		// Get User Info from Session
		$userEmail = $this->getAuthService()->getStorage()->read();
		$user = $userTable->getUserByEmail($userEmail);
		if ($user)      //== $this->identity())
		{}
		else {
			return $this->redirect()->toRoute('home');
		}
		$this->_dir = realpath($fileManagerDir); //.
		      //DIRECTORY_SEPARATOR.
		     // $user->id;
	}
	
	public function indexAction() {
		// TODO Auto-generated UserManager::indexAction() default action
		$uploadTable = $this->getServiceLocator()->get('UploadTable');
        $userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
        // Get User Info from Session
        $userEmail = $this->getAuthService()->getStorage()->read();
        $user = $userTable->getUserByEmail($userEmail);
        //throw new \Zend\File\Transfer\Exception\InvalidArgumentException('b��d'.var_dump($uploadTable->getSharedUploadsForUserId($user->id)).' '.var_dump($user->id));
        $viewModel = new ViewModel( array('myUploads' => $uploadTable->getUploadsByUserId($user->id),'sharedUploads' => $uploadTable->getSharedUploadsForUserId($user->id), ));
      
    return $viewModel;
	}
	
	public function getAuthService()
	{
		if (! $this->authservice) {
			$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
			$dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,'user','email','password', 'MD5(?)');
			$authService = new AuthenticationService();
			$authService->setAdapter($dbTableAuthAdapter);
			$this->authservice = $authService;
		}
		return $this->authservice;
	}
		
	public function getUploadsByUserId($userId)
	{
		$userId = (int) $userId;
		$rowset = $this->tableGateway->select(	array('user_id' => $userId));
		return $rowset;
	}
	
	public function deleteeAction()
	{
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) {
			return $this->redirect()->toRoute('upploadmanager');
		}    	
		$request = $this->getRequest(); 
		if ($request->isPost()) {
			$del = $request->getPost('del', 'No');
			//throw new \Zend\File\Transfer\Exception\InvalidArgumentException(var_dump($del));
			if ($del == 'Yes') {
				$id = (int) $request->getPost('id');
				$uploadTable = $this->getServiceLocator()->get('UploadTable');
				$config = $this->getServiceLocator()->get('config');
				$path=$config['module_config']['upload_location'];
				$filename = $path.$uploadTable->getUpload($id)->filename;
				$uploadTable->deleteUpload($id);
				//*****************************delating file****************************************		
				if (file_exists($filename))
				{
					unlink($filename);
				}
				//**********************************************************************************
			}
			// Redirect to list of uploads
			return $this->redirect()->toRoute('upploadmanager');
		}
		$uploadTable = $this->getServiceLocator()->get('UploadTable');
		return array('id' => $id, 'MyUpload' => $uploadTable->getUpload($id));
	}
	
	public function deleteAction() //with java script onclick
	{
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) {
			return $this->redirect()->toRoute('upploadmanager');
		}
				$uploadTable = $this->getServiceLocator()->get('UploadTable');
				$path = '/home/bupiotr/.apps/http/__default__/0/Project_01/1.0.0/data/uploads/';
				$filename = $path.$uploadTable->getUpload($id)->filename;
				$uploadTable->deleteUpload($id);
				//*****************************delating file****************************************
				if (file_exists($filename))
				{
					unlink($filename);
				}
				//**********************************************************************************
			return $this->redirect()->toRoute('upploadmanager');
	}
	
	public function addAction()
	{	
		$form = new UploadForm();
		$request=$this->request;
		$uploadFile = $this->params()->fromFiles('filename'); 
		$form->setData($request->getPost());
		if ($request->isPost()){
			$uploadFile = $this->params()->fromFiles('filename');
			$form->setData($request->getPost());
			//************************form validate***********************************
			if ($form->IsValid()) { 
				// Fetch Configuration from Module Config
				$uploadPath = $this->getFileUploadLocation();
				// Save Uploaded file	
				$adapter = new \Zend\File\Transfer\Adapter\Http(); 	
				$adapter->setDestination($uploadPath);
				// checking if file already exist
				$uploadTable = $this->getServiceLocator()->get('UploadTable');
				$filenameapp = $uploadFile['name'];			
				$rowfile   = $uploadTable->getUploadfilename($filenameapp); 
		
				if ($this->request->getPost()->get('override')=='not_override')
				{
					$exists = new NotExists('/home/bupiotr/.apps/http/__default__/0/Project_01/1.0.0/data/uploads')	;
					$adapter->addValidators(array($exists),$uploadFile['name']);
				}
						if (!$adapter->isValid()){
							$dataError = $adapter->getMessages();
							$error = array();
							foreach($dataError as $key=>$row)
							{
								$error[] = $row;
							}
							$form->setMessages(array('filename'=>$error ));
						}
						else {
						if ($adapter->receive($uploadFile['name'])) {
							// File upload sucessfull			
							$userEmail = $this->getAuthService()->getStorage()->read();
							$userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
							$user = $userTable->getUserByEmail($userEmail);
							$exchange_data = array();
							if (!$rowfile == NULL)
							{
								$exchange_data['id'] = $rowfile->id;
							}
							$exchange_data['label'] = $this->request->getPost()->get('label');
							$exchange_data['filename'] = $uploadFile['name'];
							$exchange_data['user_id'] = $user->id;
							$upload = new Upload();
							$upload->exchangeArray($exchange_data);	
							$uploadTable->saveUpload($upload);
							//displaing list of sharing uploads
							//it's need to function getSharedUsers($upload_id)
							$lastupload = $uploadTable->getlastUpload();
								if ($this->request->getPost()->get('sharing')=='shared')
								{
									$upload_id = $lastupload;
									$user_id = $request->getPost()->get('users');
									$shared_by = $user->id;
									$uploadTable->addSharing($upload_id, $user_id, $shared_by);
								}
							return $this->redirect()->toRoute('upploadmanager' , array('action' => 'add'));
							}
						}
					} //end form is valid
				else {//echo form is not valid;
					$form->populateValues($request->getPost());
					$viewModel = new ViewModel(array(
							'error' => true,
							'form' => $form,
					));
					$viewModel->setTemplate('users/upploadmanager/add');
					return $viewModel;
				} //end form is not valid
		}//end is post
		//*****************************************************************************************
		$uploadTable = $this->getServiceLocator()->get('UploadTable');
		$userTable = $this->getServiceLocator()->get('Users\Model\UserTable');
		$Users = $userTable->fetchAll();
		//Convert rowset to array with column name
			$Names = array();
			foreach ($Users as $User) {
				$Names[$User->id] = $User->name;
			}
		$userEmail = $this->getAuthService()->getStorage()->read();
		$user = $userTable->getUserByEmail($userEmail);
		$form = new UploadForm();
		$form->get('users')->setValueOptions($Names);
		$viewModel = new ViewModel(array('form' =>$form, 'sharedUsers' => $uploadTable->getSharedUploadsmakebyme($user->id)));	
		return $viewModel;
	}
	
	// file is allready uploaded
	/*public function fileisupploadedAction() 
	{
		//$uploadFile = $this->uploadFiles;
		//$filenameapp = $uploadFile['name'];
		//throw new \Zend\File\Transfer\Exception\InvalidArgumentException('  '.var_dump($uploadFile));
		$this->view->filename=$this->filename;
	    $viewModel = new ViewModel(array('filename'=>$this->filename));
		return $viewModel;		
	} 
	
	// return from  fileisupploadedAction() message
	public function fileexistexitAction()
	{
		//$viewModel = new ViewModel();
		return $this->redirect()->toRoute(upploadmanager , array(
		'controller' => 'upploadmanager',
		'action' => 'add',
		));
	
	}*/
	
	
	
	
	public function removeshareAction()
	{
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) {
			return $this->redirect()->toRoute('upploadmanager');
		}
		$request = $this->getRequest();
		if ($request->isPost()) {
			$del = $request->getPost('del', 'No');
			if ($del == 'Yes') {
				$id = (int) $request->getPost('id');
				$uploadTable = $this->getServiceLocator()->get('UploadTable');
				$uploadTable->removeSharing($id);
				//******************************************************************
			}
			// Redirect to list of uploads
			return $this->redirect()->toRoute('upploadmanager',array('controller' => 'upploadmanager', 'action'=>'add'));
		}
		$uploadTable = $this->getServiceLocator()->get('UploadTable');
		return array('id' => $id, 'MySharing' => $uploadTable->getSheredUpload($id));
	}
	
	public function editAction()
	{
		$id = (int) $this->params()->fromRoute('id', 0);
		if (!$id) {
			throw new \Zend\File\Transfer\Exception\InvalidArgumentException('  '.var_dump($id));
			return $this->redirect()->toRoute('upploadmanager', array(
					'action' => 'add'
			));
		}
		
		// Get the Album with the specified id.  An exception is thrown
		// if it cannot be found, in which case go to the index page.
		try {
			$uploadTable = $this->getServiceLocator()->get('UploadTable');
		}
		catch (\Exception $ex) {
			return $this->redirect()->toRoute('upploadmanager', array(
					'action' => 'index'
			));
		}
		$upload = $uploadTable->getUpload($id);
		$form  = new UploadForm();
		$form->bind($upload);
		$form->get('submit')->setAttribute('value', 'Confirm');
		
		$request = $this->getRequest();
		if ($request->isPost()) {
			$form->setData($request->getPost());
		
			if ($form->isValid()) {
				$uploadTable->saveUpload($upload);
		
				// Redirect to list of albums
				return $this->redirect()->toRoute('upploadmanager', array('action' => 'index'));
			}
		}
		return array(
				'id' => $id,
				'form' => $form,
		);
	}
	
	public function fileDownloadAction()
	{
		$uploadId = $this->params()->fromRoute('id');
		$uploadTable = $this->getServiceLocator()->get('UploadTable');
		$upload = $uploadTable->getUpload($uploadId);
		// Fetch Configuration from Module Config
		$uploadPath = $this->getFileUploadLocation();
		$file = file_get_contents($uploadPath ."/" . $upload->filename);
		// Directly return the Response
		$response = $this->getEvent()->getResponse();
		$response->getHeaders()->addHeaders(array(
				'Content-Type' => 'application/octet-stream',
				'Content-Disposition' => 'attachment;filename="'
				.$upload->filename . '"',
		));
		$response->setContent($file);
		return $response;
	}
	
	public function getFileUploadLocation()
	{
		// Fetch Configuration from Module Config
	
		$config = $this->getServiceLocator()->get('config');
		return $config['module_config']['upload_location'];
	}
	
	//public function setLastUploadFile($data)
	//{
		//if (!$this->LastUploadFile) {
			//$uploadTable = $this->getServiceLocator()->get('UploadTable');
			//$this->LastUploadFile = $data; //$uploadTable->getlastUpload();;
		//}
		//return $this->LastUploadFile;
	//}
	
	//public function getLastUploadFile()
	//{
		//if (!$this->LastUploadFile) {
			//$uploadTable = $this->getServiceLocator()->get('UploadTable');
			//$this->LastUploadFile = NULL; //$uploadTable->getlastUpload();;
		//}
		//return $this->LastUploadFile;
	//}
	
	//********************************************************
	//direct file view and download conception
	//********************************************************
	
	public function showuploadedfilesAction()
	{
		$this->init();
		/*$file=urldecode($this->params()->fromRoute('id'));
		$filename = $this->_dir.DIRECTORY_SEPARATOR.$file;
		$contents = NULL;
		if (fileExists($filename)){
		$handle = fopen($filename, "r");
		$contents = fread($handle, filesize($filename));
		fclose($handle);
		}
		$viewModel = new ViewModel(array('MyUploads' =>$contents,));*/
	
		$files = array();
		if (is_dir($this->_dir)){
			$handle = opendir($this->_dir);
			if ($handle){
				while (false !== ($entry=readdir($handle))){
					if ($entry != "." && $entry != "..") {
						$files[] = $entry;
					}
				}
			}
			closedir($handle);
		}
		return new ViewModel(array('myUploads'=>$files));
	}
	
	public function directfileDownloadAction()
	{
		$this->init();
		$file =  urldecode($this->params()->fromRoute('id'));
		$filename = $this->_dir.DIRECTORY_SEPARATOR.$file;	
		/*if (file_exists($filename)){
			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attatchment; filename='.basename($file));
			header('Content-Transfer-Encoding: binary');
			header('Expiren: 0');
			header('Pragma: public');
			header('Cache-Length: '.filesize($filename));
			ob_clean();
			flush();
			readfile($filename);
			//$file_read = file_get_contents($filename);
			exit();
			//return  $file_read;
			
		}*/
			//another variant
			//$this->view->layout()->disableLayout(); //dodane
			$file_read = file_get_contents($filename);
			//$file_read = readfile($filename);
			// Directly return the Response
			$response = $this->getEvent()->getResponse();
			$response->getHeaders()->addHeaders(array(
				'Content-Type' => 'application/octet-stream',
			    'Content-Type: image/jpeg',
			    'Content-Disposition' => 'attachment;filename="'.$file . '"',));
			$response->setContent($file_read);
			return $response;
	}
	
	//download with zend/stream
	/*public function fileAction()
	{
	        $file = '/path/to/my/file.txt';

	        $response = new Stream();
	        $response->setStream(fopen($file, 'r'));
	        $response->setStatusCode(200);
	        $response->setStreamName(basename($file));

	        $headers = new Headers();
	        $headers->addHeaders(array(
			            'Content-Disposition' => 'attachment; filename="' . basename($file) .'"',
			            'Content-Type' => 'application/octet-stream',
			            'Content-Length' => filesize($file)
			        ));
	        $response->setHeaders($headers);
	        return $response;
	}*/
	
	public function viewuploadedfilesAction()
	{
		$this->init();
		$file=urldecode($this->params()->fromRoute('id'));
		$viewModel = new ViewModel(array('id' => $file));
		return $viewModel;
	}
	
	public function viewimageAction()
	{
		$this->init();
		$file=$this->params()->fromRoute('id');
		$filename = $this->_dir.DIRECTORY_SEPARATOR.$file;	
		if (file_exists($filename)){		
			//$handle = fopen($filename, "r");
			//$contents = fread($handle, filesize($filename));
			//fclose($handle);	
			header("Content-Type: image/jpeg");
			readfile($filename);
		}
	}
	
}
